package plus.easydo.starter.file;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import plus.easydo.core.result.DataResult;
import plus.easydo.core.result.R;
import plus.easydo.starter.file.exception.FileStoreException;

import java.math.BigDecimal;
import java.util.Objects;


/**
 * 文件存储服务的抽象实现类，实现共有方法
 * @author laoyu
 * @version 1.0
 */
public abstract class CommonFileStoreServer<INDEX, INPUT_FILE, RESULT_FILE, TEMPLATE> extends DataResult<Object> implements FileStoreService<INDEX, INPUT_FILE, RESULT_FILE, TEMPLATE>{

    protected static final String SLASH = "/";
    protected static final String NULL = "null";

    protected FileStoreObject<INDEX,INPUT_FILE> fileStoreObject;
    protected INPUT_FILE file;
    protected String filePath;
    protected String fileName;
    protected String groupName;
    protected BigDecimal fileKbSize;

    @Autowired
    protected TEMPLATE template;

    @Override
    public TEMPLATE getTemplate() {
        return this.template;
    }

    @Override
    public R<FileResult<INDEX>> save(FileStoreObject<INDEX, INPUT_FILE> fileStoreObject) {
        validationFile(fileStoreObject.getFile());
        this.fileStoreObject = fileStoreObject;
        this.file = fileStoreObject.getFile();
        this.fileName = buildFileName(fileStoreObject.getFile(),fileStoreObject.getFileName());
        this.filePath = buildFilePath(fileStoreObject.getFilePath());
        this.groupName = buildGroupName(fileStoreObject.getGroupName());
        this.fileKbSize = getFileKbSize(file);
        return ok(buildResult());
    }

    @Override
    public void validationFile(INPUT_FILE inputFile) {
        if(Objects.isNull(inputFile)){
            throw new FileStoreException("file is empty");
        }

    }

    @Override
    public String buildFilePath(String filePath) {
        if (CharSequenceUtil.isBlank(filePath) || NULL.equals(filePath)){
            filePath = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.PURE_DATE_PATTERN) + SLASH;
        }else if (filePath.endsWith(SLASH)){
            filePath = filePath + SLASH;
        }
        return filePath;
    }

    @Override
    public FileResult<INDEX> buildResult() {
        FileResult<INDEX> result = new FileResult<>();
        result.setGroupName(groupName);
        result.setFileName(fileName);
        result.setFilePath(filePath);
        result.setFileSize(fileKbSize);
        return result;
    }
}
